import api from '../../utils/api.js'
import {
	login,
	captcha
} from '../../utils/urls.js'
var Util = require( '../../utils/util.js' );
const app = getApp()
const url=app.globalData.url
Page({
	data: {
	  username: 'admin',
		password: '3',
		captcha:"",
		jpgimage:"",
	},
	login: function (e) {
		let username = e.detail.value.username
		let password = e.detail.value.password
		let captchaCode = e.detail.value.captcha
		if (!username) {
			wx.showToast({
				title: '用户名不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}
		if (!password) {
			wx.showToast({
				title: '密码不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}
		if (!captchaCode) {
			wx.showToast({
				title: '验证码不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}
		//
		console.log(Util.json2Form({name:this.data.username,password:this.data.password,captcha:this.data.captcha}))
		wx.request({
			url: url+login,
			
			data:{name:this.data.username,password:this.data.password,captcha:this.data.captcha},
			method:"POST",
			header:getApp().globalData.header,
			success:res=>{
				 console.log(res.data)
				 if(res.data=="ok"){
					wx.showToast({
						title:"登录成功",
						icon: 'sucess',
						duration: 2000
					})
					if (res.header["Set-Cookie"] != null) {
						//设置cookie
						getApp().globalData.header["Cookie"] += res.header["Set-Cookie"]
					}
					wx.switchTab({
						url: '/pages/index/index',
					})
				 }
				 else{
					wx.showToast({
						title:res.data,
						icon: 'none',
						duration: 2000
					})
					this.nextPic()
				 }
			},
			
		})
	},
	nextPic: function () {
	
		wx.request({
			url: url+captcha,
		 header:getApp().globalData.header,
      responseType: 'arraybuffer',
      success:res=>{
        let url ='data:image/png;base64,'+wx.arrayBufferToBase64(res.data)
          this.setData({
						jpgimage:url
					})
					if (res.header["Set-Cookie"] != null) {
						//设置cookie
						getApp().globalData.header["Cookie"] += res.header["Set-Cookie"]
					}

      },
      fail:err=>{
        reject(err)
      }
			
		})
	},
	onLoad: function () {
		this.nextPic()
	}
})